package com.google.code.jholidays.io;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import com.google.code.jholidays.core.DescriptorCollection;
import com.google.code.jholidays.io.jdbc.JdbcReader;


/**
 * This test depends on SQLite JDBC driver. You must add jdbc driver to your
 * classpath before executing this test
 * 
 * @author tillias
 * 
 */
public class JdbcReaderTest {

    @Test
    public void testRead() throws ClassNotFoundException, SQLException {
	Connection conn = prepareConnection();

	final String tableName = "events";
	final int recordsCount = 10;

	assertFillData(tableName, conn, recordsCount);

	JdbcReader reader = new JdbcReader(conn, tableName);
	DescriptorCollection collection = reader.read();

	assertNotNull(collection);
	assertEquals(recordsCount, collection.size());

	conn.close();
    }

    protected Connection prepareConnection() throws ClassNotFoundException,
	    SQLException {
	Class.forName("org.sqlite.JDBC");
	Connection conn = DriverManager.getConnection("jdbc:sqlite:test_db");

	assertNotNull(conn);

	return conn;
    }

    protected void assertFillData(String tableName, Connection conn,
	    int recordsCount) throws SQLException {
	// create table
	assertNotNull(tableName);

	PreparedStatement pr = null;
	Statement st = null;

	try {
	    st = conn.createStatement();
	    st.execute("drop table if exists " + tableName);

	    st.execute("CREATE TABLE " + tableName
		    + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
		    + "name TEXT NOT NULL, " + "description TEXT NOT NULL, "
		    + "parent_id INTEGER, " + "expression TEXT NOT NULL )");

	    pr = conn
		    .prepareStatement("insert into "
			    + tableName
			    + " (name,description,parent_id,expression) values(?,?,?,?)");

	    for (int i = 0; i < recordsCount; ++i) {
		pr.setString(1, String.valueOf(i));
		pr.setString(2, String.valueOf(i));
		pr.setString(4, "25.12");

		assertEquals(1, pr.executeUpdate());
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    fail(e.getMessage());
	} finally {
	    if (pr != null)
		pr.close();
	    if (st != null)
		st.close();
	}
    }

}
